package com.ramos.kuaixiao.driver.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.MyView.refresh.SwipyRefreshLayout;
import com.ramos.kuaixiao.MyView.refresh.SwipyRefreshLayoutDirection;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.db.OrderDB;
import com.ramos.kuaixiao.entity.FindOrderDetail;
import com.ramos.kuaixiao.entity.OrderDetail;
import com.ramos.kuaixiao.shops.adapter.MallOrderAdapter;
import com.ramos.kuaixiao.shops.entity.MallOrder;
import com.ramos.kuaixiao.ui.OrderFragment;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;

public class DriverOrderFragment extends Fragment implements OnClickListener, SwipyRefreshLayout.OnRefreshListener {
    private static final String TAG = "DriverOrderFragment";
    private View mView;
    private Context mContext;
    private final int TOP_REFRESH = 1;
    private final int BOTTOM_REFRESH = 2;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    private DriverOrderAdapter mAdapter;
    private List<FindOrderDetail> productList = new ArrayList<>();
    private List<FindOrderDetail> temList = new ArrayList<>();
    CommonLoading loading;
    private int page = 1;
    private RecyclerView mRecyclerView;
    private SwipyRefreshLayout mRefreshLayout;
    private LinearLayoutManager mLinearLayoutManager;
    private boolean mIsRefresh = true;
    private LinearLayout ll_unfinished_none;
    TextView tv_all;
    TextView tv_uncheck;
    TextView tv_pay;
    TextView tv_new;
    int currentPage = 1;
    OrderDB db;
    private boolean mIsLocalDB = false;
    String customerId = "";
    String ss = "sss=";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        container = (ViewGroup) mView.getParent();
        if (container != null) {
            container.removeView(mView);
        }
        return mView;
    }

    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        initView();
        if(StringUtil.isEmpty(SharedPreference.getPreferString("customerId"))) {
            //initUid();
        } else {
            //customerId = SharedPreference.getPreferString("customerId");
            //initData(0, 1);
        }
        updateAllOrder();
    }

    private void updateAllOrder() {
        try {
            String url = NetUtils.FIND_ALL_ORDER;
            long time = new OrderDB().getMaxModifyTime();
           /* String path = url + SharedPreference.getPreferString("dealer") + "&employerId=" + SharedPreference.getPreferString("id")
                    + "&userId=" + SharedPreference.getPreferString("id")+ "&modifyTime=" + time;*/

            String path ="http://182.61.22.235/quick-erp/productorder/getorderbycondition.shtml?pageNum=100&pageNow=1&dealerId=xgx&employerId=2072&userId=2072&modifyTime="+time;
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            App.isOrderUpdating = true;

            Log.d(TAG, "path :" + path);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "ORDER_ALL:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS, result);
                            JSONObject data = jsonObejct.getJSONObject("data");
                            final List<FindOrderDetail> temList = JSONArray.parseArray(data.getJSONArray("rows").toString(), FindOrderDetail.class);
                            if(temList.size() > 0){
                                //CommUtil.d(App.mContext, TAG, "UpdateOrder:temList=" + temList.size());
                                CommUtil.d(App.mContext, TAG, "List.size()=" + temList.size());
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        OrderDB customerDB = new OrderDB();
                                        if (customerDB.updateAllOrder(temList) == 0) {
                                            //将订单结果更新
                                            App.mOrderList.addAll(temList);
                                            //UpdateOrderTask product4 = new UpdateOrderTask();
                                            //product4.executeOnExecutor(Executors.newCachedThreadPool());
                                        } else {
                                            App.isOrderUpdating = false;

                                        }
                                    }
                                }).start();
                            }else {
                                App.isOrderUpdating = false;
                                initDriver(1,1);
                            }
                        }else {
                            App.isOrderUpdating = false;
                            initDriver(1,1);
                        }
                    } catch (Exception e) {
                        App.isOrderUpdating = false;

                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    App.isOrderUpdating = false;

                }
            });
        } catch (Exception e) {
            App.isOrderUpdating = false;

            e.printStackTrace();
        }
    }

    private void initUid() {
        try {
            String url = NetUtils.FIND_UID;
            String path = url + SharedPreference.getPreferString("id");
            Log.d(TAG, "path:" + path);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            org.json.JSONObject jsonObejct = user.getJSONObject("data");
                            customerId = jsonObejct.getString("id");
                            if(!StringUtil.isEmpty(customerId)){
                                initData(0, 1);
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    if (mIsRefresh) {
                        loading.dismiss();
                    }
                    sendMessagea(UPLOAD_FAIL, "fail");
                }
            });
        } catch (Exception e) {
            if (mIsRefresh) {
                loading.dismiss();
            }
            sendMessagea(UPLOAD_FAIL, "fail");
            e.printStackTrace();
        }
    }

    private void initView() {
        mContext = getActivity();
        mView = LayoutInflater.from(mContext).inflate(R.layout.fragment_mall_order, null);
        mView.findViewById(R.id.title_reback).setVisibility(View.INVISIBLE);

        tv_all = (TextView) mView.findViewById(R.id.tv_all);
        tv_uncheck = (TextView) mView.findViewById(R.id.tv_uncheck);
        tv_pay = (TextView) mView.findViewById(R.id.tv_pay);
        tv_new = (TextView) mView.findViewById(R.id.tv_new);
        tv_all.setOnClickListener(this);
        tv_uncheck.setOnClickListener(this);
        tv_pay.setOnClickListener(this);
        tv_new.setOnClickListener(this);
        ll_unfinished_none = (LinearLayout) mView.findViewById(R.id.ll_unfinished_none);
        mRefreshLayout = (SwipyRefreshLayout) mView.findViewById(R.id.allListView);
        mRefreshLayout.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.list_task);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mAdapter = new DriverOrderAdapter(getActivity(), productList);
        mRecyclerView.setAdapter(mAdapter);
        ll_unfinished_none.setVisibility(View.VISIBLE);
        SharedPreference.setPreferString("isOldVersion", "1");
        db= new OrderDB();
    }

    private void initData(int page, int currentPage) {
        try {
            if(StringUtil.isEmpty(customerId)){
                ll_unfinished_none.setVisibility(View.VISIBLE);
                return;
            }

            String url = NetUtils.FIND_MALL_ORDER;
            String path = url + SharedPreference.getPreferString("dealer") + "&pageIndex=" + page + getValue(currentPage) + "&customerId="+customerId;
            Log.d(TAG, "path:" + path);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            if (mIsRefresh) {
                loading = new CommonLoading(getActivity());
                loading.setLoadText("获取数据中...");
            }
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    if (mIsRefresh) {
                        loading.dismiss();
                    }
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS, result);
                        } else {
                            sendMessagea(UPLOAD_FAIL, "fail");
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        sendMessagea(UPLOAD_FAIL, "fail");
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    if (mIsRefresh) {
                        loading.dismiss();
                    }
                    sendMessagea(UPLOAD_FAIL, "fail");
                }
            });
        } catch (Exception e) {
            if (mIsRefresh) {
                loading.dismiss();
            }
            sendMessagea(UPLOAD_FAIL, "fail");
            e.printStackTrace();
        }
    }

    private String getValue(int currentPage) {
        if (currentPage == 2) {
            return "&orderStatus=SUBM";
        } else if (currentPage == 3) {
            return "&orderStatus=KEEP";
        } else if (currentPage == 4) {
            return "&orderStatus=0000";
        } else {
            return "";
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:

                    break;
                case UPLOAD_FAIL:
                    mRefreshLayout.setRefreshing(false);
                    if (productList.size() == 0) {
                        if (mRefreshLayout != null) {
                            mRefreshLayout.setVisibility(View.GONE);
                        }
                        ll_unfinished_none.setVisibility(View.VISIBLE);
                    }
                    mIsRefresh = true;
                    break;
                default:
                    break;
            }
        }
    };

    private void addTasks(List<FindOrderDetail> orders) {
        Collections.sort(orders, new Comparator<FindOrderDetail>() {

            @Override
            public int compare(FindOrderDetail o1, FindOrderDetail o2) {
                long time1 = 0;
                long time2 = 0;
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                    Date date = new Date();
                    time1 = sdf.parse(o1.getOrderDate()).getTime();
                    time2 = sdf.parse(o2.getOrderDate()).getTime();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 按照时间进行降序排列
                if (time1 > time2) {
                    return -1;
                }
                if (time1 == time2) {
                    return 0;
                }
                return 1;
            }
        });
    }

    @Override
    public void onRefresh(SwipyRefreshLayoutDirection direction) {
        if (direction == SwipyRefreshLayoutDirection.TOP) {
            mIsRefresh = false;
            dataOption(TOP_REFRESH);
        } else {
            mIsRefresh = false;
            dataOption(BOTTOM_REFRESH);
        }
    }

    class Product extends AsyncTask<String, String, String> {
        List<FindOrderDetail> list;
        List<OrderDetail> detaillist;
        List<String> orderImageList;

        public Product(List<FindOrderDetail> type) {
            list = type;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                for (int i = 0; i < list.size(); i++) {
                    detaillist = JSONArray.parseArray(list.get(i).getOrderDetailList(), OrderDetail.class);
                    orderImageList = new ArrayList<>();
                    if (detaillist != null && detaillist.size() > 0) {
                        for (OrderDetail orderDetail : detaillist) {
                            String imgURL = Utils.showImg(orderDetail.getProductInfoId(), orderDetail.getProductBarCode());
                            if (!StringUtil.isEmpty(imgURL)) {
                                orderImageList.add(imgURL);
                            }
                        }
                    }
                    list.get(i).setOrderImageList(orderImageList);
                    Log.d("Product", "orderImageList " + i + " " + orderImageList.size());
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            Log.d("Product", "onPostExecute " + list.size());

            mAdapter.notifyDataSetChanged();
        }
    }


    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_all:
                if (currentPage != 1) {
                    page = 0;
                    currentPage = 1;
                    //initData(0, 1);
                    initDriver(1,1);
                    setText(1);
                }
                break;

            case R.id.tv_new:
                if (currentPage != 2) {
                    page = 0;
                    currentPage = 2;
                    //initData(0, 2);
                    initDriver(1,2);
                    setText(2);
                }
                break;
            case R.id.tv_uncheck:
                if (currentPage != 3) {
                    page = 0;
                    currentPage = 3;
                    //initData(0, 3);
                    initDriver(1,3);
                    setText(3);
                }
                break;
            case R.id.tv_pay:
                if (currentPage != 4) {
                    page = 0;
                    currentPage = 4;
                    //initData(0, 4);
                    initDriver(1,4);
                    setText(4);
                }
                break;

            default:
                break;
        }
    }

    private void initDriver(int page, int currentPage) {
        if (page == 1) {
            productList.clear();
        }
        temList.clear();
        Log.d(TAG, "result " + productList.size());
        temList = db.findAllDriverOrder(page, 20, currentPage);
        if (temList.size() > 0) {
            productList.addAll(temList);
            addTasks(productList);
            if (mRefreshLayout != null) {
                mRefreshLayout.setVisibility(View.VISIBLE);
            }
            ll_unfinished_none.setVisibility(View.GONE);
            mAdapter.notifyDataSetChanged();
            Product product = new Product(productList);
            product.executeOnExecutor(Executors.newCachedThreadPool());
        } else if (productList.size() == 0) {
            Log.d(TAG, "result productList 0 ");
            if (mRefreshLayout != null) {
                mRefreshLayout.setVisibility(View.GONE);
            }
            ll_unfinished_none.setVisibility(View.VISIBLE);
        }
        mRefreshLayout.setRefreshing(false);
        mIsRefresh = true;
    }

    private void setText(int i) {
        if (i == 1) {
            tv_all.setTextColor(getResources().getColor(R.color.title_mall));
            tv_new.setTextColor(getResources().getColor(R.color.black));
            tv_uncheck.setTextColor(getResources().getColor(R.color.black));
            tv_pay.setTextColor(getResources().getColor(R.color.black));
            tv_all.setBackgroundColor(getResources().getColor(R.color.adjust_line));
            tv_new.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_uncheck.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_pay.setBackgroundColor(getResources().getColor(R.color.color_white));
        } else if (i == 2) {
            tv_all.setTextColor(getResources().getColor(R.color.black));
            tv_new.setTextColor(getResources().getColor(R.color.title_mall));
            tv_uncheck.setTextColor(getResources().getColor(R.color.black));
            tv_pay.setTextColor(getResources().getColor(R.color.black));
            tv_all.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_new.setBackgroundColor(getResources().getColor(R.color.adjust_line));
            tv_uncheck.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_pay.setBackgroundColor(getResources().getColor(R.color.color_white));
        } else if (i == 3) {
            tv_all.setTextColor(getResources().getColor(R.color.black));
            tv_new.setTextColor(getResources().getColor(R.color.black));
            tv_uncheck.setTextColor(getResources().getColor(R.color.title_mall));
            tv_pay.setTextColor(getResources().getColor(R.color.black));
            tv_all.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_new.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_uncheck.setBackgroundColor(getResources().getColor(R.color.adjust_line));
            tv_pay.setBackgroundColor(getResources().getColor(R.color.color_white));
        } else if (i == 4) {
            tv_all.setTextColor(getResources().getColor(R.color.black));
            tv_new.setTextColor(getResources().getColor(R.color.black));
            tv_uncheck.setTextColor(getResources().getColor(R.color.black));
            tv_pay.setTextColor(getResources().getColor(R.color.title_mall));
            tv_all.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_new.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_uncheck.setBackgroundColor(getResources().getColor(R.color.color_white));
            tv_pay.setBackgroundColor(getResources().getColor(R.color.adjust_line));
        }
    }

    private void dataOption(int option) {
        switch (option) {
            case TOP_REFRESH:
                // 下拉刷新
                productList.clear();
                page = 1;
                //initData(0, currentPage);
                initDriver(1,currentPage);
                break;
            case BOTTOM_REFRESH:
                // 上拉加载更多
                ++page;
                //initData(page, currentPage);
                initDriver(page, currentPage);
                break;
        }
    }
}
